#include "enemy.h"
#include "../affiliate/collider.h"
#include "../stats/stats.h"
#include "../affiliate/affiliate_bar.h"
void enemy::init()
{
    actor::init();
    normal = spriteAnima::createAnima(this,"./assets/sprite/ghost-Sheet.png",2.0f,"enemy normal");
    hurt = spriteAnima::createAnima(this,"./assets/sprite/ghostHurt-Sheet.png",2.0f,"enemy hurt");
    die = spriteAnima::createAnima(this,"./assets/sprite/ghostDead-Sheet.png",2.0f,"enemy die");
    hurt -> setActive(false);
    die -> setActive(false);
    die -> setLoop(false);
    current = normal;
    collider_ = collider::createCollider(this,normal->getSize(),Type::CIRCLE,"enemy collider_");
    std::string count = std::to_string(game_.getEnemyCount());
    count = "enemy" + count;
    stats_ = stats::createStats(this,count.c_str(),100,100,10,10);
    game_.addEnemyCount();
    hpBar = affiliate_bar::createABar(this,glm::vec2(normal->getSize().x,10),ANCHOR_BOTTOM_CENTER);
    hpBar->set_offset(hpBar->get_offset() + glm::vec2(0,normal->getSize().y / 2.0f));
    setType(nodeType::ENEMY);
    //SDL_Log("enemy init");
}

void enemy::update(float dt)
{
    actor::update(dt);
    if(target_&& target_->isActive()){
        aim_target(target_);
        move(dt);
        attack();
    }
    checkState();
    remove();
}

enemy* enemy::createEnemy(node *parent, glm::vec2 pos, player *target)
{
    enemy *ey = new enemy();
    ey->init();
    ey->set_target(target);
    ey->setWorldPosition(pos);
    if(parent)parent->addChild(ey);
    return ey;
}

void enemy::aim_target(player *target)
{
    if(target == nullptr)
        return;
    auto dir = target->getWorldPosition() - this->getWorldPosition();
    dir= glm::normalize(dir);
    speed_= dir * max_speed_;
}

void enemy::checkState(){
    state newState = NORMAL;
    if(stats_ && stats_->getHp() <= 0){
        newState = DIE;
    }else if(stats_->isInvincible()){
        newState = HURT;
    }else{
        newState = NORMAL;
    }
    if(newState != state_){
        changeState(newState);
    }
}
void enemy::changeState(state newState){
    current->setActive(false);
    switch(newState){
        case NORMAL:
            current = normal;
            current->setActive(true);
            break;
        case HURT:
            current = hurt;
            current->setActive(true);
            break;
        case DIE:
            current = die;
            current->setActive(true);
            game_.addScore(score_);
            break;
    }
    state_ = newState;
}

void enemy::remove()
{
    if(die->isFinished()){
        need_remove_= true;
    }
    //SDL_Log("enemy remove");
}

void enemy::attack()
{
    if(!collider_||!target_||target_->getCollider() == nullptr){
        SDL_Log("collider is null");
        return;
    }
    if(collider_->isColliding(target_->getCollider())){
        if(stats_ && target_->getStats()){
            target_->getStats()->takeDamage(stats_->getdamage());
        }
    }
}
